package permission

import (
	"gin_demo/internal/consts"
	"gin_demo/internal/model"
	"gin_demo/utility"
	"time"

	"github.com/gin-gonic/gin"
)

func List(ctx *gin.Context, req PageList) {
	list := []model.Permission{}
	var count int64
	tx := consts.App.DB.Limit(req.Limit).Offset(req.Page - 1).Find(&list).Count(&count)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "权限加载失败")
	} else {
		res := PermissionRes{
			Count: count,
			List:  list,
		}
		utility.Success(ctx, res)
	}
}

func Create(ctx *gin.Context, req AddPermissionReq) {
	list := model.Permission{
		Name:   req.Name,
		Path:   req.Path,
		Method: req.Method,
	}
	tx := consts.App.DB.Create(&list)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "权限添加失败")
	} else {
		utility.Success(ctx, list)
	}
}

func Update(ctx *gin.Context, req UpdatePermissionReq) {
	list := model.Permission{
		Name: req.Name,
		Path: req.Path,
	}
	tx := consts.App.DB.Model(&list).Where("id=?", req.Id).Updates(&list)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "权限更新失败")
	} else {

		utility.Success(ctx, list)
	}
}

func Delete(ctx *gin.Context, req SoftDeleteReq) {
	list := model.Permission{}
	tx := consts.App.DB.Model(&list).Where("id=?", req.Id).Update("deleted_at", time.Now())
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "权限删除失败")
	} else {

		utility.Success(ctx, "删除成功")
	}
}
